<script setup lang="ts">
import { ref, shallowRef, watch } from 'vue';
import { useWatcher } from '@sa/alova/client';
import type { TreeOption } from 'naive-ui';
import { alova } from '@/service/request';

defineOptions({
  name: 'PorTree'
});

interface Props {
  url?: string;
  data?: TreeOption[];
  clearable?: boolean;
  labelField?: string;
  keyField?: string;
  multiple?: boolean;
  childrenField?: string;
  checkable?: boolean;
  cascade?: boolean;
  defaultCheckedKeys?: Array<number | string>;
}

const props = withDefaults(defineProps<Props>(), {
  dataUrl: undefined,
  data: undefined,
  clearable: true,
  labelField: 'name',
  keyField: 'id',
  multiple: false,
  childrenField: 'children',
  checkable: true,
  cascade: true,
  defaultCheckedKeys: () => []
});

const dynamicData = shallowRef<TreeOption[]>(props.data || []);

function processData(data: Api.Node[]) {
  dynamicData.value = data.map(recursive);
}

function recursive(item: Api.Node): TreeOption {
  const result: TreeOption = {
    ...item,
    children: item.children ? item.children.map(recursive) : undefined
  };

  return result;
}

const getData = (url: string) => {
  return alova.Get<Api.Node[]>(url);
};

const url = ref(props.url || '');
watch(
  () => props.url,
  (newUrl: string | undefined) => {
    url.value = newUrl || '';
  }
);

const { loading } = useWatcher(
  // 必须设置为返回method实例的函数
  () => getData(url.value),
  [url],
  {
    immediate: true
  }
).onSuccess(({ data }) => {
  processData(data);
});
</script>

<template>
  <NTree
    :loading="loading"
    :clearable="clearable"
    :data="dynamicData"
    :label-field="labelField"
    :key-field="keyField"
    :children-field="childrenField"
    :multiple="multiple"
    :default-checked-keys="defaultCheckedKeys"
    :cascade="cascade"
    :checkable="checkable"
  ></NTree>
</template>

<style scoped></style>
